<template>
  <div class="page-wapper">
    <!-- 组织架构 -->
    <div class="container" style="padding: 0">
      <!-- 顶部 -->
      <header class="group_header">
        <div v-if="$isSupperAdmin()" class="header_left_box">
          <span class="label">选择机构：</span>
          <OrgSelect
            v-model="orgInfo.orgId"
            :defaultOrgName="orgInfo.orgName"
            @change="getPageData"
          />
        </div>
        <div class="t_c">组织架构</div>
        <div v-if="$isSupperAdmin()" class="header_right_box">
          <el-button-group>
            <el-button
              size="small"
              :loading="pageLoading"
              type="primary"
              @click="getPageData"
            >
              搜索
            </el-button>
            <el-button size="small" @click="handleReset"> 重置 </el-button>
          </el-button-group>
        </div>
      </header>
      <!-- 主体 -->
      <div class="group_part" v-loading="pageLoading">
        <div class="group_content">
          <GroupBox v-if="groupData.length" :list="groupData" />
          <div v-else class="empty_box">
            <div class="desc">暂无组织数据</div>
            <el-button
              v-if="$hasPermission($permission.GROUP_SAVE_OR_UPDATE)"
              type="primary"
              @click="createMethod"
            >
              新增组织
            </el-button>
          </div>
        </div>
      </div>
    </div>

    <!-- 编辑组织弹框 -->
    <GroupFormDialog
      ref="groupFormDialogRef"
      :orgId="orgInfo.orgId"
      @refresh="getPageData"
    />

    <!-- 编辑组织人员弹框 -->
    <GroupUserFormDialog
      ref="groupUserFormDialogRef"
      :orgId="orgInfo.orgId"
      @refresh="getPageData"
    />
  </div>
</template>

<script>
import {
  ref,
  nextTick,
  getCurrentInstance,
  computed,
  provide,
  onMounted,
  reactive,
} from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { useStore } from "vuex";
import GroupBox from "./components/GroupBox.vue";
import GroupFormDialog from "./components/GroupFormDialog.vue";
import GroupUserFormDialog from "./components/GroupUserFormDialog.vue";
import OrgSelect from "../../components/OrgSelect.vue";

export default {
  name: "GroupManage",
  components: { GroupBox, GroupFormDialog, GroupUserFormDialog, OrgSelect },
  setup() {
    const { proxy } = getCurrentInstance();
    const $api = proxy.$api;
    const store = useStore();

    const userInfo = computed(() => store.state.user.userInfo);

    // 编辑组织弹框
    const groupFormDialogRef = ref(null);
    const openFormDialog = (row, isAddChild = false) => {
      nextTick(() => {
        groupFormDialogRef.value.open(row, isAddChild);
      });
    };
    // const closeFormDialog = () => {
    //   nextTick(() => {
    //     groupFormDialogRef.value.close();
    //   });
    // };

    // 编辑组织人员弹框
    const groupUserFormDialogRef = ref(null);
    const openGroupUserFormDialog = (row) => {
      nextTick(() => {
        groupUserFormDialogRef.value.open(row);
      });
    };
    // const closeGroupUserFormDialog = () => {
    //   nextTick(() => {
    //     groupUserFormDialogRef.value.close();
    //   });
    // };

    // 机构选择组件绑定的数据
    const orgInfo = reactive({
      orgId: null,
      orgName: null,
    });

    const groupData = ref([]);

    const pageLoading = ref(false);

    const getPageData = () => {
      const orgId = orgInfo.orgId;
      // 因为超级管理员可能没有绑定机构，所以增加此判断
      if (!orgId) {
        groupData.value = [];
        return;
      }
      pageLoading.value = true;
      $api.group
        .treeList({
          orgId,
        })
        .then((res) => {
          pageLoading.value = false;
          // 强制刷新视图重新渲染
          groupData.value = [];
          nextTick(() => {
            groupData.value = res.data;
          });
        })
        .catch((err) => {
          pageLoading.value = false;
          console.error("getPageData error: ", err);
        });
    };

    // 新建
    const createMethod = () => {
      if (!orgInfo.orgId) {
        return ElMessage.warning("请先选择机构");
      }
      openFormDialog();
    };

    // 编辑
    const editMethod = (row) => {
      openFormDialog(row);
    };

    // 添加下级
    const createChildMethod = (row) => {
      openFormDialog(row, true);
    };

    // 编辑成员
    const editMemberMethod = (row) => {
      openGroupUserFormDialog(row);
    };

    // 删除组织
    const deleteGroupMethod = (row) => {
      ElMessageBox.confirm(
        `确定要删除【${
          row.groupName.length > 10
            ? row.groupName.slice(0, 10) + "..."
            : row.groupName
        }】吗？`,
        "提示",
        { type: "warning" }
      )
        .then(() => {
          deleteTableData([row.id]);
        })
        .catch(() => {});
    };

    // 删除内容接口
    const deleteTableData = (ids) => {
      pageLoading.value = true;
      $api.group
        .removeByIds({
          ids,
        })
        .then((res) => {
          ElMessage.success("删除成功！");
          getPageData();
        })
        .catch((err) => {
          console.error("deleteTableData error: ", err);
        })
        .finally(() => {
          pageLoading.value = false;
        });
    };

    // 重置
    const handleReset = () => {
      // 此数据必须在 dom 挂载之后初始化，否则 v-model 绑定数据无法流向子组件
      orgInfo.orgId = userInfo.value.orgId;
      orgInfo.orgName = "aaa";
      getPageData();
    };

    /**
     * 初始化
     */

    provide("editGroup", editMethod);
    provide("createChild", createChildMethod);
    provide("editMember", editMemberMethod);
    provide("deleteGroup", deleteGroupMethod);

    onMounted(() => {
      handleReset();
    });

    return {
      orgInfo,
      groupData,
      pageLoading,
      groupFormDialogRef,
      groupUserFormDialogRef,
      createMethod,
      editMethod,
      createChildMethod,
      getPageData,
      handleReset,
    };
  },
};
</script>

<style lang="less" scoped>
.group_header {
  border-bottom: 1px solid #eee;
  padding: 20px;
  position: relative;
  .header_left_box {
    position: absolute;
    top: 50%;
    transform: translateY(-50%);
    left: 20px;
    display: flex;
    align-items: center;
    .label {
      font-size: 14px;
      line-height: 28px;
    }
  }
  .header_right_box {
    position: absolute;
    top: 50%;
    transform: translateY(-50%);
    right: 20px;
    display: flex;
    align-items: center;
  }
}

.group_part {
  flex: 1;
  overflow: auto;
  background-color: #f2f2f2;
  .group_content {
    position: relative;
    padding: 20px;
    text-align: center;
  }
  .group_row {
    // display: flex;
    // justify-content: center;
    // align-items: center;
    position: relative;
    height: 63px;
  }
  .group_cell_wrapper {
    // position: relative;
    // display: flex;
    // flex-shrink: 0;
    // justify-content: center;
    // align-items: center;
    // padding: 20px;
  }
  .link_line {
    position: absolute;
    top: 0;
    left: 50%;
    z-index: 0;
    height: 100%;
    width: 500px;
    transform: translateX(-50%);
    box-sizing: border-box;
    &.top {
      border-top: 2px solid #409eff;
    }
    &.bottom {
      border-bottom: 2px solid #409eff;
    }
  }
  .group_cell {
    border: 1px solid #409eff;
    padding: 10px 20px;
    border-radius: 4px;
    position: absolute;
    z-index: 1;
    // & + .group_cell {
    //   margin-left: 40px;
    // }
    &.top_line::before {
      display: block;
      content: "";
      position: absolute;
      top: 0;
      left: 50%;
      width: 2px;
      background: #409eff;
      height: 20px;
      transform: translate(-50%, -100%);
    }
    &.bottom_line::after {
      display: block;
      content: "";
      position: absolute;
      bottom: 0;
      left: 50%;
      width: 2px;
      background: #409eff;
      height: 20px;
      transform: translate(-50%, 100%);
    }
  }

  .empty_box {
    padding-top: 25vh;
    text-align: center;
    .desc {
      color: #999;
      letter-spacing: 2px;
      margin-bottom: 20px;
    }
  }
}
</style>
